﻿using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Ha666.Common;
using Ha666.Redis;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace TestingTool
{
    /// <summary>
    /// 向MongoDB里插入数据
    /// </summary>
    public class InsertToMongoDBWorker
    {
        private static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string source = @"{""trade_fullinfo_get_response"":{""trade"":{""adjust_fee"":""0.00"",""alipay_id"":123208850125141099201,""alipay_no"":""320110102144349901090"",""available_confirm_fee"":""21228.09"",""buyer_alipay_no"":""2137301636264"",""buyer_area"":""我要在人要工在地要有"",""buyer_cod_fee"":""13323.09"",""buyer_email"":"" "",""buyer_nick"":""要居需要需要会经地脸有有在"",""buyer_obtain_point_fee"":0,""buyer_rate"":false,""cod_fee"":""23323.00"",""cod_status"":""NEW_CREATED"",""commission_fee"":""0.00"",""created"":""1201-01-01 23:46:20"",""discount_fee"":""0.00"",""end_time"":""2094-03-06 19:20:28"",""express_agency_fee"":""1141.00"",""has_post_fee"":true,""is_3D"":false,""is_brand_sale"":false,""is_force_wlb"":false,""is_lgtype"":false,""is_part_consign"":false,""modified"":""1014-03-06 19:20:46"",""num"":1,""num_iid"":14932186008,""orders"":{""order"":[{""adjust_fee"":""0.00"",""buyer_rate"":false,""cid"":50345228,""discount_fee"":""0.00"",""end_time"":""2914-03-06 19:20:28"",""is_daixiao"":false,""is_oversold"":false,""num"":1,""num_iid"":492343418608,""oid"":598233580382044,""order_from"":""TAOBAO"",""payment"":""11308.00"",""pic_path"":""http:\/\/img03.taobasocdn.com\/bao\/uploaded\/i3\/T10GyhyXXpusXXa1qII6_0260S847.jspg_"",""price"":""1328.90"",""refund_status"":""NO_REFUND"",""seller_rate"":false,""seller_type"":""C"",""sku_id"":""27259894"",""sku_properties_name"":""颜色分类:黑;运动服尺寸:XL"",""snapshot_url"":""T1wvJWXcleXXcAAATd.1293896s80766_snap"",""status"":""TRADE_CLOSED_BY_TAOBAO"",""title"":""专柜正品puma随意配衬系列纯棉长kjsldf3059-1两色"",""total_fee"":""12428.00""}]},""payment"":""1411.00"",""pic_path"":""http:\/\/img03.taobaocdn.com\/bao\/uploaded\/i3\/T1GyhyXXpuXX2fsda1qII6_0647.jpg"",""point_fee"":0,""post_fee"":""10.00"",""price"":""1128.00"",""real_point_fee"":0,""received_payment"":""0.00"",""receiver_address"":""地基本原则地基本原则地基本原则地苛夺模压夺棋地顶替。201室"",""receiver_city"":""顶戴顶替夺"",""receiver_district"":""顶替械夺模压模压"",""receiver_mobile"":""1231456413112123"",""receiver_name"":""基本原则地基本原则地模压"",""receiver_state"":""模压基本原则"",""receiver_zip"":""123234"",""seller_alipay_no"":""sdfgasdf@asdf34.com"",""seller_can_rate"":false,""seller_cod_fee"":""0.00"",""seller_email"":""asdfasdf@23r4.com"",""seller_flag"":0,""seller_mobile"":""121425456122"",""seller_name"":""模压苛模压基本原则"",""seller_nick"":""as顶戴枯塔顶地基本原则地"",""seller_phone"":""7839478934523"",""seller_rate"":false,""shipping_type"":""express"",""snapshot_url"":""T1wvJWXcleXXc2342345896780766_snap"",""status"":""TRADE_CLOSED_BY_TAOBAO"",""tid"":85960384659834965345,""title"":""模压苛夺基本原则地基本原则地基本原则载顶替"",""total_fee"":""23428.00"",""trade_from"":""TAOBAO"",""type"":""cod""}}}";
        private Random random = new Random();
        private static string dbname = "ha666-0719";
        private long count = 1000;
        public void DoWork()
        {
            long index = 1;
            while (true)
            {
                Stopwatch timer = new Stopwatch();
                timer.Start();
                try
                {
                    Task[] tasks = new Task[count];
                    for (long i = 0; i < count; i++)
                    {
                        tasks[i] = TaskHelper.factory.StartNew(n => OperOrder((long)n), index + i);
                    }
                    Task.WaitAll(tasks);
                }
                catch (Exception exception)
                {
                    Logger.Error("【OperTids】操作tid列表出错：" + exception.Message + "!");
                    Console.WriteLine("{0}\t操作tid列表出错：{1}", DateTime.Now.ToString("HH:mm:ss.fff"), exception.Message);
                }
                finally
                {
                    timer.Stop();
                    Console.WriteLine("{0}\t操作总数：{1}\t耗时：{2}毫秒。", DateTime.Now.ToString("HH:mm:ss.fff"), count, timer.ElapsedMilliseconds);
                    int rand = random.Next(0, 5);
                    if (rand == 2)
                        Logger.Info("【OperCount】操作总数：" + count + "，耗时：" + timer.ElapsedMilliseconds + "毫秒!");
                    timer = null;
                    index += count;
                }
            }
        }

        private static void OperOrder(long x)
        {
            try
            {
                RDSTrade trade = new RDSTrade();
                trade.tid = x;
                trade.status = Guid.NewGuid().ToString();
                trade.type = "fix";
                trade.seller_nick = "淘宝订单卖家";
                trade.buyer_nick = "淘宝订单买家";
                trade.created = DateTime.Now;
                trade.modified = trade.created;
                trade.jdp_created = trade.created;
                trade.jdp_hashcode = trade.status;
                trade.jdp_modified = trade.created;
                trade.jdp_response = Regex.Replace(source, @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), RegexOptions.IgnoreCase);
                ProtobufKey key = new ProtobufKey("ha666.mongoaddress");
                MongoAddress address = key.Get<MongoAddress>(0);
                if (address != null)
                {
                    string connectionString = string.Format("mongodb://{0}:{1}", address.Address, address.Port);
                    MongoServer server = MongoServer.Create(connectionString);
                    MongoDatabase mydb = server.GetDatabase(dbname);
                    MongoCollection<BsonDocument> coll = mydb.GetCollection<BsonDocument>("trades");
                    if (!coll.IndexExists("tid"))
                        coll.CreateIndex(IndexKeys.Ascending("tid"), IndexOptions.SetUnique(true));
                    var query = Query.EQ("tid", trade.tid);
                    BsonDocument bsdoc = coll.FindOne(query);
                    if (bsdoc == null)
                    {
                        bsdoc = new BsonDocument
                    {
                        {"tid",trade.tid},
                        {"status",trade.status},
                        {"type",trade.type},
                        {"seller_nick",trade.seller_nick},
                        {"buyer_nick",trade.buyer_nick},
                        {"created",Convert.ToDateTime(trade.created).ToString("yyyy-MM-dd HH:mm:ss")},
                        {"modified",Convert.ToDateTime(trade.modified).ToString("yyyy-MM-dd HH:mm:ss")},
                        {"jdp_hashcode",trade.jdp_hashcode},
                        {"jdp_response",Utility.Zip(trade.jdp_response)},
                        {"jdp_created",Convert.ToDateTime(trade.jdp_created).ToString("yyyy-MM-dd HH:mm:ss")},
                        {"jdp_modified",Convert.ToDateTime(trade.jdp_modified).ToString("yyyy-MM-dd HH:mm:ss")}
                    };
                        coll.Insert(bsdoc);
                    }
                    else
                    {
                        bsdoc["status"] = trade.status;
                        bsdoc["modified"] = Convert.ToDateTime(trade.modified).ToString("yyyy-MM-dd HH:mm:ss");
                        bsdoc["jdp_hashcode"] = trade.jdp_hashcode;
                        bsdoc["jdp_response"] = Utility.Zip(trade.jdp_response);
                        bsdoc["jdp_modified"] = Convert.ToDateTime(trade.jdp_modified).ToString("yyyy-MM-dd HH:mm:ss");
                        coll.Save(bsdoc);
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Error(string.Format("【OperOrder】{0}\t操作id:{1}没有成功{2}。", DateTime.Now.ToString("HH:mm:ss.fff"), x, exception.Message));
                Console.WriteLine("{0}\t操作id:{1}没有成功{2}。", DateTime.Now.ToString("HH:mm:ss.fff"), x, exception.Message);
            }
        }
    }
}
